//
//  FWLoginViewController.m
//  JayZhou
//
//  Created by fanwu on 15/4/26.
//  Copyright (c) 2015年 ND. All rights reserved.
//

#import "FWLoginViewController.h"
#import "AppDelegate.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "LZDUITextField.h"
#import "ViewController.h"

#define kLastUserPhone @"lastUserName"
#define kRunNum @"runTimes"
#define kPhoneNum @"18759107777"
#define kPwd @"123456"
@interface FWLoginViewController ()
@property(strong, nonatomic) UIImageView * userIcon;
@property(strong, nonatomic) UITextField * phoneField;
@property(strong, nonatomic) LZDUITextField * passwordField;
@property(strong, nonatomic) UIButton * userNameClearBtn;
@property(strong, nonatomic) UIButton * pwdClearBtn;
@property(strong, nonatomic) UIButton * loginBtn;
@property(strong, nonatomic) UIButton * registBtn;
@property(nonatomic) BOOL isPhoneOk;
@property(nonatomic) BOOL isPwdOk;
@end

@implementation FWLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSUInteger  runNum = [[NSUserDefaults standardUserDefaults] integerForKey:kRunNum];
    if (runNum == 0) {
        _firstRun = YES;
    }
    
    CGFloat width = CGRectGetWidth(self.view.bounds);
    
    UIImageView * backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@" "]];
    backgroundImageView.frame = self.view.bounds;
    backgroundImageView.contentMode =  UIViewContentModeScaleAspectFill;
    backgroundImageView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:backgroundImageView];
    
    UIButton * forgetPwdBtn = [[UIButton alloc] initWithFrame:CGRectMake(16, 28, 60, 30)];
    [forgetPwdBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    forgetPwdBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [forgetPwdBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [forgetPwdBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [forgetPwdBtn addTarget:self action:@selector(forgetPasswd:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetPwdBtn];
    
    self.registBtn = [[UIButton alloc] initWithFrame:CGRectMake(width - 16 - 16 - 30, 28, 60, 30)];
    [self.registBtn setTitle: @"  注册" forState:UIControlStateNormal];
    self.registBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.registBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.registBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [self.registBtn addTarget:self action:@selector(doReg:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.registBtn];
    
//    self.userIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"user_icon"]];
//    self.userIcon.frame = CGRectMake(width / 2 - 88 / 2, 88, 88, 88);
//    [self.view addSubview: self.userIcon];
    
    UIImageView * seperator1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line_sep"]];
    seperator1.frame = CGRectMake(16, 88 + 88 + 60, width - 16 -16, 1);
    seperator1.alpha = 0.2f;
    [self.view addSubview:seperator1];
    
    self.userNameClearBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 28, 28)];
    [self.userNameClearBtn setImage:[UIImage imageNamed:@"clear_btn"] forState:UIControlStateNormal];
    [self.userNameClearBtn setImage:[UIImage imageNamed:@"clear_btn_click"] forState:UIControlStateHighlighted];
    [self.userNameClearBtn addTarget:self action:@selector(clearText:) forControlEvents:UIControlEventTouchUpInside];

    
    UIImageView * phoneView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_phone"]];
    phoneView.frame = CGRectMake(0, 0, 34, 17);
    phoneView.contentMode = UIViewContentModeLeft;
    
    
    self.phoneField = [[UITextField alloc] initWithFrame:CGRectMake(16 + 17, 88 + 88 + 60 + 1, width - 16 -16 -17, 48)];
    self.phoneField.borderStyle = UITextBorderStyleNone;
    self.phoneField.font = [UIFont systemFontOfSize:13];
    self.phoneField.textColor = [UIColor whiteColor];
    self.phoneField.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneField.rightViewMode = UITextFieldViewModeWhileEditing;
    self.phoneField.rightView = self.userNameClearBtn;
    self.phoneField.leftView = phoneView;
    self.phoneField.delegate = self;
    self.phoneField.leftViewMode = UITextFieldViewModeAlways;
    self.phoneField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"请输入您的电话号码" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5]}];
    [self.view addSubview:self.phoneField];
    
    UIImageView * seperator2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line_sep"]];
    seperator2.frame = CGRectMake(16, 88 + 88 + 60 + 1 + 48, width - 16 -16, 1);
    seperator2.alpha = 0.2f;
    [self.view addSubview:seperator2];
    
    self.pwdClearBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    [self.pwdClearBtn setImage:[UIImage imageNamed:@"clear_btn"] forState:UIControlStateNormal];
    [self.pwdClearBtn setImage:[UIImage imageNamed:@"clear_btn_click"] forState:UIControlStateHighlighted];
    [self.pwdClearBtn addTarget:self action:@selector(clearText:) forControlEvents:UIControlEventTouchUpInside];

    
    UIImageView * pwdView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_pwd"]];
    pwdView.frame = CGRectMake(0, 0, 34, 17);
    pwdView.contentMode = UIViewContentModeLeft;
    
    self.passwordField = [[LZDUITextField alloc] initWithFrame:CGRectMake(16 + 17, 88 + 88 + 60 + 1 + 48 +1, width - 16 -17 - 16, 48)];
    self.passwordField.borderStyle = UITextBorderStyleNone;
    self.passwordField.secureTextEntry = YES;
    self.passwordField.keyboardType = UIKeyboardTypeASCIICapable;
    self.passwordField.font = [UIFont systemFontOfSize:13];
    self.passwordField.textColor = [UIColor whiteColor];
    self.passwordField.rightViewMode = UITextFieldViewModeWhileEditing;
    self.passwordField.rightView = self.pwdClearBtn;
    self.passwordField.delegate = self;
    self.passwordField.leftView = pwdView;
    self.passwordField.leftViewMode = UITextFieldViewModeAlways;
    self.passwordField.returnKeyType = UIReturnKeySend;
    self.passwordField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"请输入您的密码" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5]}];
    
    [self.view addSubview:self.passwordField];
    
    UIImageView * seperator3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line_sep"]];
    seperator3.frame = CGRectMake(16, 88 + 88 + 60 + 1 + 48 + 1 + 48, width - 16 -16, 1);
    seperator3.alpha = 0.2f;
    [self.view addSubview:seperator3];
    
    self.loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(16, 88 + 88 + 60 + 1 + 48 + 1 + 48 + 1 + 16, width - 16 -16, 40)];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginBtn setBackgroundColor:[UIColor colorWithRed:0.86 green:0.3 blue:0.5 alpha:1]];
    [self.loginBtn setBackgroundColor:[UIColor grayColor]];
    [self.loginBtn setEnabled:NO];
    [self.loginBtn addTarget:self action:@selector(doLogin:) forControlEvents:UIControlEventTouchUpInside];
    self.loginBtn.layer.cornerRadius = 1.8f;
    [self.view addSubview:self.loginBtn];
    
    UILabel * info = [[UILabel alloc] initWithFrame:CGRectMake(0, 88 + 88 + 60 + 1 + 48 + 1 + 48 + 1 + 16 + 40 +24, width, 10)];
    info.text = @"也可以使用以下方式登录";
    info.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.8];
    info.font = [UIFont systemFontOfSize:11];
    info.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:info];
    info.hidden = YES;
    
    UIButton * qqLogin = [[UIButton alloc] initWithFrame:CGRectMake((width - 90 - 16) /2, 88 + 88 + 60 + 1 + 48 + 1 + 48 + 1 + 16 + 40 +24 + 10 + 16, 45, 45)];
    [qqLogin setImage:[UIImage imageNamed:@"QQ_login"] forState:UIControlStateNormal];
    [self.view addSubview:qqLogin];
    [qqLogin setHidden:YES];
    
    UIButton * sinaLogin = [[UIButton alloc] initWithFrame:CGRectMake((width - 90 - 16) /2 + 16 + 45, 88 + 88 + 60 + 1 + 48 + 1 + 48 + 1 + 16 + 40 +24 + 10 + 16, 45, 45)];
    [sinaLogin setImage:[UIImage imageNamed:@"weibo_login"] forState:UIControlStateNormal];
    [self.view addSubview:sinaLogin];
    [sinaLogin setHidden:YES];
    
    UITapGestureRecognizer * recoginzer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignKeyboard:)];
    [self.view addGestureRecognizer:recoginzer];
    
}

/**
 *  收回键盘
 *
 *  @param recoginzer
 */
- (void)resignKeyboard:(UITapGestureRecognizer *)recoginzer{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self.navigationController.navigationBar setShadowImage:[UIImage imageNamed:@"transparent"]];

    NSString * lastPhoneNum = [[NSUserDefaults standardUserDefaults] objectForKey:kLastUserPhone];
    if (lastPhoneNum && lastPhoneNum.length > 0) {
        self.phoneField.text = lastPhoneNum;
        self.isPhoneOk = YES;
    }

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

/**
 *  处理回车键登录
 */
- (BOOL) textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.passwordField) {
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        
        if([self canClickLogin]){
            [self doLogin:nil];
        }
    }
    return NO;
}
-(BOOL)textFieldShouldClear:(UITextField *)textField{
    if(_passwordField == textField){
        return NO;
    }
    return YES;
}
#pragma mark - 验证输入

#pragma mark 校验是否允许点击登录
- (BOOL)canClickLogin {
    if(self.isPhoneOk && self.isPwdOk){
        [self.loginBtn setEnabled:YES];
        [self.loginBtn setBackgroundColor:[UIColor colorWithRed:0.86 green:0.3 blue:0.5 alpha:1]];
        return YES;
    }
    else{
        [self.loginBtn setEnabled:NO];
        [self.loginBtn setBackgroundColor:[UIColor grayColor]];
        return NO;
    }
}

#pragma mark 限制手机号最多输入11位与状态检测
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSInteger strLength = textField.text.length - range.length + string.length;
    
    if(textField == self.phoneField){
        if (strLength > 11){
            return NO;
        }else if(strLength >= 3){
            self.isPhoneOk = YES;
        }else{
            self.isPhoneOk = NO;
        }
    }else if(textField == self.passwordField){
        if(strLength >= 6){
            self.isPwdOk = YES;
        }else{
            self.isPwdOk = NO;
        }
    }
    
    [self canClickLogin];
    
    if (range.location > 0 && range.length == 1 && string.length == 0)
    {
        // Stores cursor position
        UITextPosition *beginning = textField.beginningOfDocument;
        UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
        NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length;
        
        // Save the current text, in case iOS deletes the whole text
        NSString *text = textField.text;
        
        // Trigger deletion
        [textField deleteBackward];
        
        
        // iOS deleted the entire string
        if (textField.text.length != text.length - 1)
        {
            textField.text = [text stringByReplacingCharactersInRange:range withString:string];
            
            // Update cursor position
            UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset];
            UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
            [textField setSelectedTextRange:newSelectedRange];
        }
        return NO;
    }
    
    return YES;
}


#pragma mark keyboard up
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self animateTextField:textField up:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self animateTextField:textField up:NO];
}

- (void)animateTextField:(UITextField *)textField up:(BOOL) up{
    const int movementDistance = 80;
    const float movementDuration = .3f;
    
    int movement = up ? -movementDistance : movementDistance;
    
    [UIView animateWithDuration:movementDuration delay:.0f options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    } completion:nil];
}

- (IBAction)clearText:(id)sender{
    if (sender == self.userNameClearBtn) {
        self.phoneField.text = @"";
        self.isPhoneOk = NO;
    }else if(sender == self.pwdClearBtn){
        self.passwordField.text = @"";
        self.isPwdOk = NO;
    }
    [self canClickLogin];
}

- (IBAction)doLogin:(id)sender{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    
    if(_phoneField.text.length == 0){
        UIAlertView * errorView = [[UIAlertView alloc] initWithTitle:@"错误" message:@"请输入手机号" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [errorView show];
        return;
    }else if(_passwordField.text.length == 0){
        UIAlertView * errorView = [[UIAlertView alloc] initWithTitle:@"错误" message:@"请输入密码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [errorView show];
        return;
    }
    if (([_phoneField.text isEqualToString: kPhoneNum ]) && ([_passwordField.text isEqualToString:kPwd])) {
        
        ViewController *uploadVC = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
        [self.navigationController pushViewController:uploadVC animated:NO];
        self.navigationController.navigationBarHidden = YES;
        
        
    }else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:@"账号密码不对" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }
    
    
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
////    [sender setBackgroundColor:[UIColor colorWithRed:0.73 green:0.14 blue:0.36 alpha:1]];
//    NSString * phoneNum = self.phoneField.text;
//    NSString * pwd = self.passwordField.text;
//    [UCManager login:phoneNum password:pwd orgName:kUcOrgName success:^(UCCurrentUser *user) {
//        [hud hide:YES];
//        [[NSUserDefaults standardUserDefaults] setObject:phoneNum forKey:kLastUserPhone];
//        [AppDelegate sharecInstance].isLogined = YES;
//        [[AppDelegate sharecInstance] addIapPaymentObserve];
//        [self dismissViewControllerAnimated:YES completion:nil];
//        [AppDelegate sharecInstance].user = user;
//    } failure:^(NSError *error) {
//        [hud hide:YES];
//        
//        SMCExtraErrorInfo * errorInfo = error.userInfo[SMCURLStatusCodeNo2xxErrorKey];
//        NSString * errorMessage = errorInfo ? errorInfo.message : error.localizedDescription;
//        UIAlertView * errorView = [[UIAlertView alloc] initWithTitle:@"错误" message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
//        [errorView show];
//    }];
}

-(IBAction)forgetPasswd:(id)sender{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"功能待开发" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

-(IBAction)doReg:(id)sender{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"功能待开发" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

@end
